<script setup>
import Footer from "@/components/Footer.vue";
import {getCartlist,clearCart} from "@/api/cart";
import {useUserStore} from "@/stores";
import {ref,onBeforeMount} from 'vue'
import GoodsDrawer from "@/components/GoodsDrawer.vue";

const userStore=useUserStore()
const cartList=ref([])

//页面渲染前执行
onBeforeMount(async() =>{
  await getCartGoods()
})
//获取购物车列表
const getCartGoods= async ()=>{
  const res= await getCartlist(userStore.userid)
  cartList.value=res.data.data
}
//删除按钮
const del= async (id)=>{
  await ElMessageBox.confirm('确定要删除该商品吗?', '温馨提示', {
    type: 'warning',
    confirmButtonText: '确认',
    cancelButtonText: '取消'
  })
  //删除商品
  await clearCart(id)
  //重新获取商品列表
  ElMessage({ type: 'success', message: '删除成功' })
  await getCartGoods()
}


const selectAll = ref(false); // 控制所有商品的选中状态
const selectedItems = ref([]); // 存储选中的商品ID
const selectedGoodsList = ref([]); //被选中商品集合
//全选框调用函数
const updateSelectedAll = () => {
  // 如果全选复选框被选中，则将所有商品ID添加到选中列表
  if (selectAll.value) {
    selectedItems.value = cartList.value.map(item => item.id)
    selectedGoodsList.value=cartList.value
  } else {
    // 否则清空选中列表
    selectedItems.value = []
    selectedGoodsList.value=[]
  }
  // 计算总价
  calculateTotal();
}

//更新选中商品的列表
const updateSelected = () => {
  // 收集所有被选中的商品
  selectedGoodsList.value = cartList.value.filter(item => selectedItems.value.includes(item.id));
  // 收集所有被选中的商品ID
  const selectedIds = cartList.value.filter(item => selectedItems.value.includes(item.id));
  // 更新选中商品的数量
  const selectedGoods = cartList.value.filter(item => selectedIds.includes(item.id)).map(item => {
    return {
      ...item,
      quantity: selectedItems.value.includes(item.id) ? item.goodsNum : 0
    }
  })
  // 计算总价
  calculateTotal(selectedGoods);

}
//计算选中商品的总价

const calculateTotal = () => {
  let total = 0;
  for (const item of cartList.value) {
    if (selectedItems.value.includes(item.id)) {
      total =total+ item.price * item.goodsNum;
    }
  }
  return total // 格式化为两位小数的字符串
}

//抽屉板块
const drawerVisible=ref()
const OpenDrawer = () => {
   drawerVisible.value.open({})
}

</script>

<template>
  <el-card style="max-width: 100%">
    <template #header style="text-align: center">购物车</template>

    <div class="cart" v-if="cartList.length!==0">
      <table>
        <tr>
          <th><input type="checkbox" @change="updateSelectedAll()" v-model="selectAll"></th>
          <th>图片</th>
          <th>商品名称</th>
          <th>商品介绍</th>
          <th>数量</th>
          <th>价格</th>
          <th>操作</th>
        </tr>
        <tr v-for="(item) in cartList" :key="item.id">
          <td><input type="checkbox" @change="updateSelected()" v-model="selectedItems" :value="item.id"></td>
          <td><img :src="item.img"></td>
          <td style="width: 150px">{{item.name}}</td>
          <td style="width: 200px">{{ item.info }}</td>
          <td> <el-input-number min="1" v-model="item.goodsNum" /></td>
          <td>￥{{item.price}}</td>
          <td>
            <el-button type="danger" round @click="del(item.cartId)">删除</el-button>
          </td>
        </tr>

        <tbody id="cart-items">
        <!-- 这里将用JavaScript动态添加商品 -->
        </tbody>

        <tr>
          <td colspan="2"></td>
          <td></td>
          <td id="total">总价 : ￥{{ calculateTotal().toFixed(2) }}</td>
          <el-button @click="OpenDrawer" type="primary"  round>结算</el-button>
        </tr>
      </table>
    </div>
    <el-empty v-else :image-size="200" style="height: 600px" />

  </el-card>

  <Footer></Footer>


 <!--  抽屉板块--->
  <goods-drawer ref="drawerVisible"  :goodsList="selectedGoodsList"></goods-drawer>
</template>

<style scoped>
.cart{
  background-color:#FFFFFF ;
}
body {
  font-family: Arial, sans-serif;
  margin: 0;
  padding: 20px;
  height: 1000px;
}

h1 {
  text-align: center;
}

table {
  width: 100%;
}
table th, table td {
  padding: 10px;
  text-align: center;
}
th{
  background-color: #f5f5f5;
}
input.quantity {
  width: 50px;
  text-align: center;
}
img{
  width: 190px;
  height: 180px;
}

</style>

